# Distributed.pm
# Copyright (C) 2006, 2007  Stephane Alnet
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 

#
# For more information visit http://carrierclass.net/
#
package CCNCore::Provision::Distributed;
use strict;
use warnings;
use base qw(CCNCore::Provision::Base);

=pod

    my $c = new CCNCore::Provision::Distributed($p);
    my $t = new CCNCore::IPC::Ticket;
    $c->spool_this($server_pk,$t->ticket,$spool_action);

    Send a 'spool' action that will be executed on the remote node and controlled
    locally (from the sender's point-of-view) by a ticket.

=cut

sub spool_this($$$)
{
    my $self = shift;
    my ($remote_pk,$ticket_id,$what) = @_;

    my $spool = new CCNCore::IPC::Spool;
    return $spool->spool_request_to($remote_pk,"$what ".$self->p->server_pk." $ticket_id");
}

sub send_cdn_high
{
    my $self = shift;
    my $t = shift;
    my $msg = shift;
    my $target_pk = pop; # Optional: target (edge) server

    my $count = 0;

    my $where = '';
    if(defined $target_pk)
    {
        $where = "WHERE pk = $target_pk";
        $msg .= " $target_pk";
    }

    $self->sql_do_for(<<"SQL",
        SELECT DISTINCT cdn_downstream_server FROM server $where
SQL
    sub
    {
        my $cdn_pk = shift;

        $self->spool_this($cdn_pk,$t->ticket,$msg);
        $count++;
    });
    return $count;
}

sub send_cdn_low
{
    my $self = shift;
    my $t = shift;
    my $msg = shift;
    my $target_pk = pop; # Optional: target (edge) server

    my $count = 0;

    my $sql = 'SELECT pk FROM server WHERE cdn_downstream_server = '.$self->p->server_pk;
    if(defined $target_pk)
    {
        $sql = "SELECT $target_pk AS pk"; 
    }

    $self->sql_do_for($sql,
    sub
    {
        my $srv_pk = shift;

        $self->spool_this($srv_pk,$t->ticket,$msg);
        $count++;
    });
    return $count;
}

1;